package www.study.chatgpt.api.zhihu.service;



import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import www.study.chatgpt.api.zhihu.model.IZhiHuApi;
import www.study.chatgpt.api.zhihu.model.req.AnsData;
import www.study.chatgpt.api.zhihu.model.req.ReqData;
import org.slf4j.Logger;
import java.io.IOException;

import com.alibaba.fastjson.JSON;


@Service
public class ZhiHuApi implements IZhiHuApi {
    private Logger logger = LoggerFactory.getLogger(ZhiHuApi.class);

    @Override
    public ReqData queryQuestions(String cookie) throws IOException {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpGet get = new HttpGet("https://www.zhihu.com/api/v4/creators/question_route/author_related/recommend?limit=20&offset=0&page_source=web_author_recommend&recom_domain_score_ab=0");//https://www.zhihu.com/da8a5ec4-f8c0-4c38-b6a0-b077d168bdba
        get.addHeader("cookie",cookie);
        CloseableHttpResponse response = httpClient.execute(get);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            String jsonStr = EntityUtils.toString(response.getEntity());
            logger.info("拉取问题数据{}",jsonStr);
            return JSON.parseObject(jsonStr, ReqData.class);
        }else {
            throw new RuntimeException("get questions error，error code is" + response.getStatusLine().getStatusCode());
        }
    }

    @Override
    public boolean answer(int id,String cookie,String text) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("https://www.zhihu.com/api/v4/questions/" + id + "/answers?include=is_visible,paid_info,paid_info_content,admin_closed_comment,reward_info,annotation_action,annotation_detail,collapse_reason,is_normal,is_sticky,collapsed_by,suggest_edit,comment_count,can_comment,content,editable_content,voteup_count,reshipment_settings,comment_permission,created_time,updated_time,review_info,relevant_info,question,excerpt,attachment,reaction_instruction,ip_info,relationship.is_authorized,voting,is_thanked,is_author,is_nothelp,is_recognized,is_labeled;mark_infos[*].url;author.vip_info,badge[*].topics;settings.table_of_content.enabled");
        post.addHeader("cookie",cookie);
        post.addHeader("content-type","application/json");
        //String paramJson = "{\"content\":\"<p><b>其实对于很多女生来说，文职类的工作，在早期是一个不错的选择。基本上就是简单做些表格处理一些文件，打印、整理一些文件，类似于打杂的这样一个工作，技术含量不高而且工作非常零碎繁杂，长期的话也不能学到很多东西。</b></p>\",\"reshipment_settings\":\"disallowed\",\"comment_permission\":\"all\",\"reward_setting\":{\"can_reward\":false,\"tagline\":\"\"},\"disclaimer_status\":\"close\",\"disclaimer_type\":\"none\",\"commercial_report_info\":{\"is_report\":false},\"commercial_zhitask_bind_info\":null,\"is_report\":false,\"push_activity\":true,\"table_of_contents_enabled\":false,\"thank_inviter_status\":\"close\",\"thank_inviter\":\"\"}";
        AnsData answerReq = new AnsData(text);
        String paramJson = JSONObject.toJSONString(answerReq);

        StringEntity stringEntity = new StringEntity(paramJson, ContentType.create("text/json", "UTF-8"));
        post.setEntity(stringEntity);

        CloseableHttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            String jsonStr = EntityUtils.toString(response.getEntity());
            logger.info("回答问题结果。id：{}", id);
            return true;
        }else {
            //System.out.println(response.getStatusLine().getStatusCode());
            throw new RuntimeException("answer Err Code is " + response.getStatusLine().getStatusCode());
        }
    }
}
